library(foreign)
setwd("~/Replication Code/")

##---Loading in data ----
anes9297 <- read.dta("./data/anes9297_subset.dta")

ccap16 <- read.dta("./data/ccap16_subset.dta")


### ANES9297 -----
dat1 <- na.omit(anes9297[c("white_int92", "white_int94",
                            "ft_rpdp92_sc", "ft_rpdp94_sc",
                            "rr92_scaled", "rr94_scaled", "V940005")])

# PID on RR
m1.pidnew <- lm(rr94_scaled ~  ft_rpdp92_sc  + rr92_scaled, 
                data = dat1, weights = V940005, 
                subset = white_int92 == white_int94)
summary(m1.pidnew)
# RR on PID
m10.pidnew <- lm(ft_rpdp94_sc ~  ft_rpdp92_sc  + rr92_scaled, 
                 data = dat1, weights = V940005, 
                 subset = white_int92 == white_int94)
summary(m10.pidnew)


### CCAP16 -----
dat2 <- na.omit(ccap16[c("p_rr_sc", "b_rr_sc", "weight_post",
                          "b_rpdp_fav_dif", "p_rpdp_fav_dif")])

# PID Favorability on RR
m1.pfav <- lm(p_rr_sc ~ b_rpdp_fav_dif + b_rr_sc, 
              data = dat2, weights = weight_post)
summary(m1.pfav)
# RR on PID Favorability
m10.pfav <- lm(p_rpdp_fav_dif ~ b_rpdp_fav_dif + b_rr_sc, 
               data = dat2, weights = weight_post)
summary(m10.pfav)


## Table -----
m1.pidnew_p <- m1.pidnew
m10.pidnew_p <- m10.pidnew
m1.pfav_p <- m1.pfav
m10.pfav_p <- m10.pfav

names(m1.pidnew_p$coefficients) <- names(coef(rr_p))
names(m10.pidnew_p$coefficients) <- names(coef(rr_p))
names(m1.pfav_p$coefficients) <- names(coef(rr_p))
names(m10.pfav_p$coefficients) <- names(coef(rr_p))

stargazer(m1.pidnew_p, m10.pidnew_p, m1.pfav_p, m10.pfav_p, 
          title = "Relationship between Partisanship and Racial Resentment. Alternative Partisanship Operationalization",
          covariate.labels = c("Relative Republican Favorability$_{t-1}$", "Racial Resentment$_{t-1}$"),
          dep.var.labels = c("Racial Resentment", "Partisanship", "Racial Resentment", "Partisanship"), 
          no.space = T, notes = c("OLS regression results. Standard errors in parentheses. Variables scaled 0-1.",
                                  "Analyses employ population weights."), 
          notes.align = "l", intercept.bottom = T,
          digits = 3, df = F, omit.stat = c("f", "adj.rsq"), align = T, star.char = c("*"), star.cutoffs = c(0.05)
)